package com.atguigu.lease.web.admin.service.impl;

import com.atguigu.lease.common.exceptions.LeaseException;
import com.atguigu.lease.common.result.ResultCodeEnum;
import com.atguigu.lease.model.entity.*;
import com.atguigu.lease.model.enums.ItemType;
import com.atguigu.lease.model.enums.LeaseStatus;
import com.atguigu.lease.web.admin.mapper.*;
import com.atguigu.lease.web.admin.service.*;
import com.atguigu.lease.web.admin.vo.attr.AttrValueVo;
import com.atguigu.lease.web.admin.vo.graph.GraphVo;
import com.atguigu.lease.web.admin.vo.room.RoomDetailVo;
import com.atguigu.lease.web.admin.vo.room.RoomItemVo;
import com.atguigu.lease.web.admin.vo.room.RoomQueryVo;
import com.atguigu.lease.web.admin.vo.room.RoomSubmitVo;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;

import java.util.ArrayList;
import java.util.List;

/**
 * @author liubo
 * @description 针对表【room_info(房间信息表)】的数据库操作Service实现
 * @createDate 2023-07-24 15:48:00
 */
@Service
public class RoomInfoServiceImpl extends ServiceImpl<RoomInfoMapper, RoomInfo>
        implements RoomInfoService {
    @Autowired
    private GraphInfoService graphInfoService;
    @Autowired
    private RoomLeaseTermService roomLeaseTermService;
    @Autowired
    private RoomPaymentTypeService roomPaymentTypeService;
    @Autowired
    private RoomFacilityService roomFacilityService;
    @Autowired
    private RoomLabelService roomLabelService;
    @Autowired
    private RoomAttrValueService roomAttrValueService;
   /*
       //出现循环依赖，ApartmentInfoService-》RoomInfoService=》ApartmentInfoService
       @Autowired
       @Lazy
       private ApartmentInfoService apartmentInfoService;
   */
    @Autowired
    private LeaseAgreementService leaseAgreementService;

    @Autowired
    private ApartmentInfoMapper apartmentInfoMapper;
    @Autowired
    private RoomInfoMapper roomInfoMapper;
    @Autowired
    private GraphInfoMapper graphInfoMapper;
    @Autowired
    private LeaseTermMapper leaseTermMapper;
    @Autowired
    private PaymentTypeMapper paymentTypeMapper;
    @Autowired
    private FacilityInfoMapper facilityInfoMapper;
    @Autowired
    private LabelInfoMapper labelInfoMapper;
    @Autowired
    private AttrValueMapper attrValueMapper;
    /**
     * todo:保存或更新房间信息
     *      涉及表：公寓表，图片表，房间-租期关系表，房间-支付方式，房间-配套，房间-标签，房间-属性值，
     *      1.判定是否更新
     *      2.saveOrUpdate()
     *      3.如果是更新，删除对应中间表数据
     *      4.最后一定保存中间表数据
     */
    @Override
    public void customSaveOrUpdate(RoomSubmitVo roomSubmitVo) {
        //1.判定是否更新
        Boolean is_update=roomSubmitVo.getId()!=null;
        //2.执行saveOrUpdate操作
        saveOrUpdate(roomSubmitVo);
        //3.如果是更新，删除对应中间表数据
        if(is_update){
            //删除图片信息
            LambdaQueryWrapper<GraphInfo> graphInfoLambdaQueryWrapper=new LambdaQueryWrapper<>();
            graphInfoLambdaQueryWrapper.eq(GraphInfo::getItemId,roomSubmitVo.getId());
            graphInfoLambdaQueryWrapper.eq(GraphInfo::getItemType, ItemType.ROOM);
            graphInfoService.remove(graphInfoLambdaQueryWrapper);
            //删除房间-租期关系
            LambdaQueryWrapper<RoomLeaseTerm> roomLeaseTermLambdaQueryMapper=new LambdaQueryWrapper<>();
            roomLeaseTermLambdaQueryMapper.eq(RoomLeaseTerm::getRoomId,roomSubmitVo.getId());
            roomLeaseTermService.remove(roomLeaseTermLambdaQueryMapper);
            //删除房间-支付方式关系
            LambdaQueryWrapper<RoomPaymentType> roomPaymentTypeLambdaQueryWrapper=new LambdaQueryWrapper<>();
            roomPaymentTypeLambdaQueryWrapper.eq(RoomPaymentType::getRoomId,roomSubmitVo.getId());
            roomPaymentTypeService.remove(roomPaymentTypeLambdaQueryWrapper);
            //删除房间-配套关系
            LambdaQueryWrapper<RoomFacility> roomFacilityLambdaQueryWrapper=new LambdaQueryWrapper<>();
            roomFacilityLambdaQueryWrapper.eq(RoomFacility::getRoomId,roomSubmitVo.getId());
            roomFacilityService.remove(roomFacilityLambdaQueryWrapper);
            //删除房间-标签关系
            LambdaQueryWrapper<RoomLabel> roomLabelLambdaQueryWrapper=new LambdaQueryWrapper<>();
            roomLabelLambdaQueryWrapper.eq(RoomLabel::getRoomId,roomSubmitVo.getId());
            roomLabelService.remove(roomLabelLambdaQueryWrapper);
            //删除房间-属性值关系
            LambdaQueryWrapper<RoomAttrValue> roomAttrValueLambdaQueryWrapper=new LambdaQueryWrapper<>();
            roomAttrValueLambdaQueryWrapper.eq(RoomAttrValue::getRoomId,roomSubmitVo.getId());
            roomAttrValueService.remove(roomAttrValueLambdaQueryWrapper);
        }
        //4.最后一定保存中间表数据
        //批量保存图片
        List<GraphVo> graphVoList = roomSubmitVo.getGraphVoList();
        if(!CollectionUtils.isEmpty(graphVoList)){
            List<GraphInfo> graphInfoList=new ArrayList<>(graphVoList.size());
            for (GraphVo graphVo : graphVoList) {
                GraphInfo graphInfo = new GraphInfo();
                graphInfo.setName(graphVo.getName());
                graphInfo.setUrl(graphVo.getUrl());
                graphInfo.setItemType(ItemType.ROOM);
                graphInfo.setItemId(roomSubmitVo.getId());
                graphInfoList.add(graphInfo);
            }
            graphInfoService.saveBatch(graphInfoList);
        }
        //批量保存房间-租期关系
        List<Long> leaseTermIds = roomSubmitVo.getLeaseTermIds();
        if(!CollectionUtils.isEmpty(leaseTermIds)){
            List<RoomLeaseTerm> roomLeaseTermList=new ArrayList<>(leaseTermIds.size());
            for (Long leaseTermId : leaseTermIds) {
                RoomLeaseTerm roomLeaseTerm = RoomLeaseTerm.builder().
                        roomId(roomSubmitVo.getId()).
                        leaseTermId(leaseTermId).build();
                roomLeaseTermList.add(roomLeaseTerm);
            }
            roomLeaseTermService.saveBatch(roomLeaseTermList);
        }
        //批量保存房间-支付方式关系
        List<Long> paymentTypeIds = roomSubmitVo.getPaymentTypeIds();
        if(!CollectionUtils.isEmpty(paymentTypeIds)){
            List<RoomPaymentType> roomPaymentTypeList=new ArrayList<>(paymentTypeIds.size());
            for (Long paymentTypeId : paymentTypeIds) {
                RoomPaymentType roomPaymentType = RoomPaymentType.builder()
                        .paymentTypeId(paymentTypeId)
                        .roomId(roomSubmitVo.getId()).build();
                roomPaymentTypeList.add(roomPaymentType);
            }
            roomPaymentTypeService.saveBatch(roomPaymentTypeList);
        }
        //批量保存房间-配套关系
        List<Long> facilityInfoIds = roomSubmitVo.getFacilityInfoIds();
        if(!CollectionUtils.isEmpty(facilityInfoIds)){
            List<RoomFacility> roomFacilityList=new ArrayList<>(facilityInfoIds.size());
            for (Long facilityInfoId : facilityInfoIds) {
                RoomFacility roomFacility = RoomFacility.builder()
                        .facilityId(facilityInfoId)
                        .roomId(roomSubmitVo.getId())
                        .build();
                roomFacilityList.add(roomFacility);
            }
            roomFacilityService.saveBatch(roomFacilityList);
        }
        //批量保存房间标签关系
        List<Long> labelInfoIds = roomSubmitVo.getLabelInfoIds();
        if(!CollectionUtils.isEmpty(labelInfoIds)){
            List<RoomLabel> roomLabelList=new ArrayList<>();
            for (Long labelInfoId : labelInfoIds) {
                RoomLabel roomLabel = RoomLabel.builder()
                        .labelId(labelInfoId)
                        .roomId(roomSubmitVo.getId()).build();
                roomLabelList.add(roomLabel);
            }
            roomLabelService.saveBatch(roomLabelList);
        }
        //批量保存房间-属性值关系
        List<Long> attrValueIds = roomSubmitVo.getAttrValueIds();
        if(!CollectionUtils.isEmpty(attrValueIds)){
            List<RoomAttrValue> roomAttrValueList=new ArrayList<>(attrValueIds.size());
            for (Long attrValueId : attrValueIds) {
                RoomAttrValue roomAttrValue = RoomAttrValue.builder()
                        .attrValueId(attrValueId)
                        .roomId(roomSubmitVo.getId()).build();
                roomAttrValueList.add(roomAttrValue);
            }
            roomAttrValueService.saveBatch(roomAttrValueList);
        }
    }

    /**
     * 根据条件，分页，查询房间详情列表
     * @param page
     * @param queryVo
     */
    @Override
    public void customPage(Page<RoomItemVo> page, RoomQueryVo queryVo) {
        roomInfoMapper.customSelectPage(page,queryVo);
    }

    /**
     * todo:逻辑：根据id获取房间详细信息
     *      业务层涉及多个表，需要自定义service
     *      涉及中间表：图片表，房间-租期关系表，房间-支付方式，房间-配套，房间-标签，房间-属性值，
     * todo:步骤；
     *      1.根据id获取房间基本信息
     *      2.根据房间中公寓id，获取公寓信息
     *      3.根据房间id 和 所属对象类型，获取图片列表
     *      4.根据房间id,获取租期列表
     *      5.根据房间id,获取支付方式列表
     *      6.根据房间id,获取配套列表
     *      7.根据房间id，获取标签列表
     *      8.根据房间id，获取属性
     *      9.将查询结果封装进对象并返回
     * @param id
     * @return
     */
    @Override
    public RoomDetailVo getDetailById(Long id) {
        //1.根据id获取房间基本信息
        RoomInfo roomInfo = getById(id);
        //2.根据房间中公寓id，获取公寓信息
        //ApartmentInfo apartmentInfo = apartmentInfoService.getById(roomInfo.getApartmentId());
        ApartmentInfo apartmentInfo = apartmentInfoMapper.selectById(roomInfo.getApartmentId());
        //3.根据房间id 和 所属对象类型，获取图片列表
        List<GraphVo> graphVoList = graphInfoMapper.selectGraphInfoVoList(id, ItemType.ROOM);
        //4.根据房间id,获取租期列表
        List<LeaseTerm> leaseTermList=leaseTermMapper.customSelectListByRoomId(id);
        //5.根据房间id,获取支付方式列表
        List<PaymentType> paymentTypesList=paymentTypeMapper.customSelectListByRoomId(id);

        //6.根据房间id,获取配套列表
        List<FacilityInfo> facilityInfoList=facilityInfoMapper.customSelectListByRoomId(id);
        //7.根据房间id，获取标签列表
        List<LabelInfo> labelInfoList=labelInfoMapper.customSelectListByRoomId(id);
        //8.根据房间id，获取属性列表
        List<AttrValueVo> attrValueVoList=attrValueMapper.customSelectListByRoomId(id);
        //将查询结果封装进roomDetailVo对象
        RoomDetailVo roomDetailVo = new RoomDetailVo();
        BeanUtils.copyProperties(roomInfo,roomDetailVo);
        roomDetailVo.setApartmentInfo(apartmentInfo);
        roomDetailVo.setGraphVoList(graphVoList);
        roomDetailVo.setPaymentTypeList(paymentTypesList);
        roomDetailVo.setLeaseTermList(leaseTermList);
        roomDetailVo.setFacilityInfoList(facilityInfoList);
        roomDetailVo.setLabelInfoList(labelInfoList);
        roomDetailVo.setAttrValueVoList(attrValueVoList);
        //返回roomDetailVo对象
        return roomDetailVo;
    }

    /**
     * todo:根据id删除房间信息,并删除中间表数据，
     *      若有租约,并且status在2 5 7，不能删除，否则删除成功
     *      涉及的中间表：图片表，房间-租期关系表，房间-支付方式，房间-配套，房间-标签，房间-属性值，
     * @param id
     */
    @Override
    public void customRemoveById(Long id) {
        // 判断房间是否在出租，
        // 根据房间id，查询status在2，5，7之间的租约
        LambdaQueryWrapper<LeaseAgreement> leaseAgreementLambdaQueryWrapper=new LambdaQueryWrapper<>();
        leaseAgreementLambdaQueryWrapper.eq(LeaseAgreement::getRoomId,id);
        //leaseAgreementLambdaQueryWrapper.in(LeaseAgreement::getStatus, Arrays.asList(2,5,7));
        //todo :优化获取租约状态
        leaseAgreementLambdaQueryWrapper.in(LeaseAgreement::getStatus,
                LeaseStatus.SIGNED.getCode(),
                LeaseStatus.WITHDRAWING.getCode(),
                LeaseStatus.RENEWING.getCode());
        long count = leaseAgreementService.count(leaseAgreementLambdaQueryWrapper);
        //如果房间在出租
        if(count>0){
            //删除失败，抛出异常，异常处理并返回失败结果
            //优化：枚举入参构造异常
            throw new LeaseException(ResultCodeEnum.ROOM_DELETE_ERROR);
        }
        //如果房间未在出租，删除中间表，并删除房间表
        //根据id删除房间
        removeById(id);
        //根据房间id,删除图片
        LambdaQueryWrapper<GraphInfo> graphInfoLambdaQueryWrapper=new LambdaQueryWrapper<>();
        graphInfoLambdaQueryWrapper.eq(GraphInfo::getItemId,id);
        graphInfoLambdaQueryWrapper.eq(GraphInfo::getItemType,ItemType.ROOM);
        graphInfoService.remove(graphInfoLambdaQueryWrapper);
        // 根据房间id,删除房间-租期关系，
        LambdaQueryWrapper<RoomLeaseTerm> roomLeaseTermLambdaQueryMapper=new LambdaQueryWrapper<>();
        roomLeaseTermLambdaQueryMapper.eq(RoomLeaseTerm::getRoomId,id);
        roomLeaseTermService.remove(roomLeaseTermLambdaQueryMapper);
        // 根据房间id,删除房间-支付方式，
        LambdaQueryWrapper<RoomPaymentType> roomPaymentTypeLambdaQueryWrapper=new LambdaQueryWrapper<>();
        roomPaymentTypeLambdaQueryWrapper.eq(RoomPaymentType::getRoomId,id);
        roomPaymentTypeService.remove(roomPaymentTypeLambdaQueryWrapper);
        // 根据房间id,删除房间-配套，
        LambdaQueryWrapper<RoomFacility> roomFacilityLambdaQueryWrapper=new LambdaQueryWrapper<>();
        roomFacilityLambdaQueryWrapper.eq(RoomFacility::getRoomId,id);
        roomFacilityService.remove(roomFacilityLambdaQueryWrapper);
        // 根据房间id,删除房间-标签，
        LambdaQueryWrapper<RoomLabel> roomLabelLambdaQueryWrapper=new LambdaQueryWrapper<>();
        roomLabelLambdaQueryWrapper.eq(RoomLabel::getRoomId,id);
        roomLabelService.remove(roomLabelLambdaQueryWrapper);
        // 根据房间id,删除房间-属性值，
        LambdaQueryWrapper<RoomAttrValue> roomAttrValueLambdaQueryWrapper=new LambdaQueryWrapper<>();
        roomAttrValueLambdaQueryWrapper.eq(RoomAttrValue::getRoomId,id);
        roomAttrValueService.remove(roomAttrValueLambdaQueryWrapper);
    }
}




